'''
文件说明：
用途：对检测结果进行评估，主要包括log-average miss rate评估参数

author: 周小龙
date：24-12-1
'''
import numpy as np
import pandas as pd
'''
the object detection evaluation tools
author: zxiaolon
date: 24-11-30
'''

def np_col(df, name):
    if isinstance(df, dict):
        return df[name]

    idx = df.columns.get_loc(name)
    bm = df._mgr
    return np.asarray(bm.blocks[bm.blknos[idx]].iget(bm.blklocs[idx]))

def lamr(mr_fppi: pd.DataFrame, samples=9)-> float:
    '''
    用途：求解log-average miss rate
    calculate the log-average miss rate on Object detection
    :param mr_fppi: pandas dataframe, include miss rate, FPPI and confidence three columns
    :param samples:
    :return:
    '''
    if len(mr_fppi) <= 1:
        return float('nan')

    miss = np_col(mr_fppi, 'miss_rate')
    fppi = np_col(mr_fppi, 'false_positives_per_image')
    ref = []
    for t in np.power(10,np.arange(-2,0.25,0.25)):
        if np.sum(fppi<=t) == 0:
            ref.append(0)
        else:
            ref.append(np.min(miss[fppi<=t]))
    log_average = np.exp(np.average(np.log(np.asarray(ref))))
    return np.around(log_average,6)